package com.isoftstone.disk.controller;

import com.isoftstone.disk.entity.RenameFile;
import com.isoftstone.disk.service.DiskService;
import com.isoftstone.platform.controller.BaseController;
import com.isoftstone.platform.entity.PadingRstType;
import com.isoftstone.platform.model.entity.FileEntity;
import org.apache.commons.fileupload.FileItem;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;

@Controller
@RequestMapping("/file")
public class DiskController  extends BaseController {
    private Logger logger = Logger.getLogger("DiskControllor");

    @Resource
    private DiskService diskService;

    @RequestMapping("/fileAll")
    public String ShowAll(){
        return  "file/fileAll";
    }


    @RequestMapping("/addFile")
    @ResponseBody
    public String addFile(MultipartHttpServletRequest request) throws IOException {
        CommonsMultipartFile cFile =
                (CommonsMultipartFile)request.getFile("filePath");
        String fileNameDesc = request.getParameter("fileName");
        FileItem fileItem =
                cFile.getFileItem();
        logger.info("fileNameDesc:" + fileNameDesc + ";filePath:" + fileItem.getName());
        if (fileItem.getName() == null
                || "".equals(fileItem.getName()))
        {
            return buildFailJsonMsg("up.load.fail",
                    null);
        }
        //上传文件到OBS服务器
        diskService.addFile(fileNameDesc,fileItem.getName(),cFile.getInputStream());
        //保存文件信息到数据库
        diskService.saveFileInfToDatabase(fileNameDesc,fileItem.getName());
        return buildSuccessJsonMsg("file.upload.success",null);
    }

    //获取文件列表
    @RequestMapping("/getFileInfolist")
    @ResponseBody
    public PadingRstType<FileEntity> getFileInfolist(@RequestParam("parentID") String parentID)  {
        System.out.println("parentID==="+parentID);
        PadingRstType<FileEntity> padingRstType = new PadingRstType<FileEntity>();
        padingRstType=diskService.getFileInfolist();
        return padingRstType;
    }

    //下载
    @RequestMapping(value = "/download/{fileId:.+}")
    @ResponseBody
    public ResponseEntity<byte[]> download(@PathVariable("fileId") String fileId) {
        ResponseEntity<byte[]> responseEntity = diskService.download(fileId);
        return responseEntity;
    }

    //移动到回收站
    @RequestMapping(value = "/recycle/{fileId:.+}")
    @ResponseBody
    public String recycle(@PathVariable("fileId") String fileId) {
        diskService.recycle(Integer.valueOf(fileId));
        return buildSuccessJsonMsg("file.upload.success",null);
    }

    //分享文件 链接
    @RequestMapping(value = "/share/{fileId:.+}")
    @ResponseBody
    public  String share(@PathVariable("fileId") String fileId) throws IOException {
        String rsp= diskService.share(fileId);
        Map<String, Object> message = new LinkedHashMap<>();
        message.put("success", true);
        message.put("msg", rsp);
        message.put("description", rsp);
        return buildSuccessJsonMsg(rsp,null);
    }

    //添加到分享中
    @RequestMapping(value = "/shareFile/{fileId:.+}")
    @ResponseBody
    public String shareFile(@PathVariable("fileId") int fileId) {
        diskService.sharing(Integer.valueOf(fileId));
        return buildSuccessJsonMsg("file.upload.success",null);
    }

    //预览
    @RequestMapping(value = "/preview/{fileId:.+}")
    @ResponseBody
    public String preview(@PathVariable("fileId") String fileId) throws IOException {
        String tempUrl;
        System.out.println("处于预览控制器~Now Preview Controller");
        System.out.println("处于"+fileId+"11111111111111");
        if(fileId.isEmpty())
            return buildSuccessJsonMsg("file.delete.fail",null);
        tempUrl=diskService.preview(fileId);
        System.out.println("文件预览控制器~Preview Controller:(preview):tempUrl="+tempUrl);
        return "{\"id\":\"lin.jpg\",\"type\":\"audio\",\"tempUrl\":\""+tempUrl+"\"}";
    }

    //新建文件夹
    @RequestMapping(value = "/newFolder")
    @ResponseBody
    public String newFolder(@RequestParam("parentId") String mid, @RequestParam("folderName")String  name) {
        diskService.newFolders(mid,name);
        return buildSuccessJsonMsg("role.grant.sucess", null);
    }

    //查询当前目录下的文件列表
    @RequestMapping(value = "/queryFolder")
    @ResponseBody
    public PadingRstType<FileEntity> queryFolder(@RequestParam("parentID") String  PId) {
        PadingRstType<FileEntity> padingRstType = new PadingRstType<FileEntity>();
        padingRstType=diskService.queryFileOfParent(Integer.valueOf(PId));
        return padingRstType;
    }

    // 添加文件到指定的目录下   -- 测试版 未完成！
    @RequestMapping(value = "/newFiles")
    @ResponseBody
    public String  newFiles(HttpServletRequest request,HttpServletRequest response,HttpSession session)  throws IOException {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");//file是form-data中二进制字段对应的name
        System.out.println(multipartFile.getSize());
        String name=  multipartFile.getName();
        diskService.addFile(name,name,multipartFile.getInputStream());
        return buildSuccessJsonMsg("role.grant.sucess", null);
    }

    //返回上级目录
    @RequestMapping("/backToPardir")
    @ResponseBody
    public String  backToPardir(@RequestParam("parentId") String parentID)  {
        System.out.println("parentID==="+parentID);
        int  parentid =diskService.backToPardir(Integer.valueOf(parentID));

        return String.valueOf(parentid);
    }

    //重命名
    @RequestMapping(value = "/updateName")
    @ResponseBody
    public String updateName( RenameFile renameFile) {
        diskService.updateName(renameFile);
        return buildSuccessJsonMsg("warehouse.update.sucess", null);
    }

}
